package com.tool_stdy.ForkJoinDemo;

import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

import com.google.common.collect.Lists;

/**
 * Created by yan_li on 2017/9/2.
 */
public class ForkJoinTest2 extends RecursiveTask<Integer> {

    private List<Integer> list;
    private static final int NUM = 100;//每个任务长度

    public ForkJoinTest2(List<Integer> list) {
        this.list = list;
    }

    @Override
    protected Integer compute() {
        int sumResult = 0;
        int size = list.size();
        if (size < NUM) {
            sumResult = count(list);
        } else {
            int middle = size / 2;
            ForkJoinTest2 task2 = new ForkJoinTest2(list.subList(0, middle));
            ForkJoinTest2 task3 = new ForkJoinTest2(list.subList(middle, size));
            task2.fork();
            task3.fork();
            sumResult = (task2.join() + task3.join());
        }
        return sumResult;
    }

    private int count(List<Integer> taskList) {
        int sum = 0;
        for (Integer target : taskList) {
            sum += target;
        }
        return sum;
    }

    public static void main(String[] args) throws Exception {
        List<Integer> ll = Lists.newArrayList();
        for (int i = 0; i < 500000; i++) {
            ll.add(i);
        }
        ForkJoinTest2 task = new ForkJoinTest2(ll);
        //通过无参的类构造器创建一个ForkJoinPool
        ForkJoinPool pool = new ForkJoinPool();
        //调用execute()方法执行任务
        long t1 = System.currentTimeMillis();
        ForkJoinTask<Integer> submit = pool.submit(task);
        System.out.println(submit.get()+"---"+(System.currentTimeMillis() - t1));
        int summ = 0;
        long t11 = System.currentTimeMillis();
        for (int i = 0; i < 500000; i++) {
            summ += i;
        }
        System.out.println(summ+"=="+(System.currentTimeMillis() - t11));
    }
}
